package com.example.eurekagateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

/**
 * 对客户端header中的Authorization信息进行简单认证
 * @author sw
 *
 */
@Component
public class TokenAuthenticationFilter extends AbstractGatewayFilterFactory {
	
	private static final String Bearer_ = "Bearer ";

	@Override
	public GatewayFilter apply(Object config) {
		// TODO Auto-generated method stub
		return (exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();
			ServerHttpRequest.Builder mutate = request.mutate();
			ServerHttpResponse response = exchange.getResponse();
			try {
				//获取header中的Authorization
				String header = request.getHeaders().getFirst("Authorization");
				if (header == null || !header.startsWith(Bearer_)) {
					throw new RuntimeException("请求头中Authorization的信息为空");
				}
				//截取Authorization Bearer
				String token = header.substring(7);
				//可把token存到redis中，此时直接在redis中判断是否由此key，有则校验通过，否则校验失败
				if(!StringUtils.isEmpty(token)) {
					System.out.println("校验通过");
					//有token，把token设置到header中，传递给后端服务
					mutate.header("userDetails", token).build();
				}else {
					//token无效
					System.out.println("token无效");
					return null;
				}
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			ServerHttpRequest build = mutate.build();
			return chain.filter((ServerWebExchange) exchange.mutate().request(build));
		};
	}
}
